/*
 * DelimitedMatrixReader.cs
 *
 * Creates dense matrices from delimited text files.
 *
 * Copyright (c) 2005, dnAnalytics. All rights reserved.
 */

using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using dnAnalytics.Resources;

namespace dnAnalytics.LinearAlgebra.IO
{
    /// <summary>
    /// Creates a <see cref="Matrix"/> from a delimited text file. If the user does not
    /// specify a delimiter, then any whitespace is used.
    /// </summary>
    /// <include file='../../../../examples/trunk/LinearAlgebra/IO/DelimitedMatrixReaderOverall.xml' path='example'/> 
    public class DelimitedMatrixReader : IMatrixReader
    {
        #region Fields
        private static Regex white = new Regex(@"\s+");
        private Regex delimiter;
        #endregion Fields

        #region Constructors
        /// <summary>
        /// Constructs a <b>DelimitedMatrixReader</b> using any whitespace as a delimiter.
        /// </summary>
        public DelimitedMatrixReader()
        {
            delimiter = white;
        }

        /// <summary>
        /// Constructs a <b>DelimitedMatrixReader</b> using the given delimiter.
        /// </summary>
        /// <param name="delimiter">The delimiter to use.</param>
        public DelimitedMatrixReader(char delimiter)
        {
            this.delimiter = new Regex(new string(delimiter, 1));
        }

        /// <summary>
        /// Constructs a <b>DelimitedMatrixReader</b> using the given delimiter.
        /// </summary>
        /// <param name="delimiter">The delimiter to use.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="delimiter"/> is <b>null</b>.</exception>
        public DelimitedMatrixReader(string delimiter)
        {
            if (delimiter == null)
            {
                throw new ArgumentNullException("delimiter", Strings.NullParameterException);
            }
            this.delimiter = new Regex(delimiter);

        }
        #endregion Constructors

        #region IMatrixReader Members

        /// <summary>
        /// Reads a <see cref="Matrix"/> from a file.
        /// </summary>
        /// <param name="file">The file to read the matrix from.</param>
        /// <returns>A matrix containing the data from the file. <b>null</b> is returned if the file is empty.</returns> 
        /// <exception cref="ArgumentNullException">If <paramref name="file"/> is <b>null</b>.</exception>
        /// <exception cref="IOException">If the file doesn't exist.</exception>
        /// <exception cref="FormatException">If a value is not a number or not in a valid format.</exception>
        /// <exception cref="OverflowException">If a value represents a number less than <see cref="Double.MinValue"/> or greater than <see cref="Double.MaxValue"/>.</exception>
        public Matrix ReadMatrix(string file)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file", Strings.NullParameterException);
            }

            if (!File.Exists(file))
            {
                throw new IOException(Strings.FileDoesNotExist);
            }
            return ReadMatrix(File.OpenRead(file), Settings.DefaultMatrixType);
        }

        /// <summary>
        /// Reads a <see cref="Matrix"/> from a <see cref="Stream"/>.
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> to read the matrix from.</param>
        /// <returns>A matrix containing the data from the <see cref="Stream"/>. <b>null</b> is returned if the <see cref="Stream"/> is empty.</returns>        
        /// <exception cref="ArgumentNullException">If <paramref name="stream"/> is <b>null</b>.</exception>
        /// <exception cref="FormatException">If a value is not a number or not in a valid format.</exception>
        /// <exception cref="OverflowException">If a value represents a number less than <see cref="Double.MinValue"/> or greater than <see cref="Double.MaxValue"/>.</exception>
        public Matrix ReadMatrix(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream", Strings.NullParameterException);
            }

            using (StreamReader reader = new StreamReader(new BufferedStream(stream)))
            {
                return ReadMatrix(reader, Settings.DefaultMatrixType);
            }
        }

        /// <summary>
        /// Reads a <see cref="Matrix"/> from a <see cref="TextReader"/>.
        /// </summary>
        /// <param name="reader">The <see cref="TextReader"/> to read the matrix from.</param>
        /// <returns>A matrix containing the data from the <see cref="TextReader"/>. <b>null</b> is returned if the <see cref="TextReader"/> is empty.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="reader"/> is <b>null</b>.</exception>
        /// <exception cref="FormatException">If a value is not a number or not in a valid format.</exception>
        /// <exception cref="OverflowException">If a value represents a number less than <see cref="Double.MinValue"/> or greater than <see cref="Double.MaxValue"/>.</exception>
        public Matrix ReadMatrix(TextReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader", Strings.NullParameterException);
            }
            return ReadMatrix(reader, Settings.DefaultMatrixType);
        }

        /// <summary>
        /// Reads an <see cref="Matrix"/> from a file.
        /// </summary>
        /// <param name="file">The file to read the matrix from.</param>
        /// <param name="matrixType">The type of matrix to return.</param>
        /// <returns>A matrix containing the data from the file. <b>null</b> is returned if the file is empty.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="file"/> is <b>null</b>.</exception>
        /// <exception cref="IOException">If the file doesn't exist.</exception>
        /// <exception cref="FormatException">If a value is not a number or not in a valid format.</exception>
        /// <exception cref="OverflowException">If a value represents a number less than <see cref="Double.MinValue"/> or greater than <see cref="Double.MaxValue"/>.</exception>
        public Matrix ReadMatrix(string file, MatrixType matrixType)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file", Strings.NullParameterException);
            }

            if (!File.Exists(file))
            {
                throw new IOException(Strings.FileDoesNotExist);
            }
            return ReadMatrix(File.OpenRead(file), matrixType);
        }

        /// <summary>
        /// Reads an <see cref="Matrix"/> from a <see cref="Stream"/>.
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> to read the matrix from.</param>
        /// <param name="matrixType">The type of matrix to return.</param>
        /// <returns>A matrix containing the data from the <see cref="Stream"/>. <b>null</b> is returned if the <see cref="Stream"/> is empty.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="stream"/> is <b>null</b>.</exception>
        /// <exception cref="FormatException">If a value is not a number or not in a valid format.</exception>
        /// <exception cref="OverflowException">If a value represents a number less than <see cref="Double.MinValue"/> or greater than <see cref="Double.MaxValue"/>.</exception>
        public Matrix ReadMatrix(Stream stream, MatrixType matrixType)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream", Strings.NullParameterException);
            }
            using (StreamReader reader = new StreamReader(new BufferedStream(stream)))
            {
                return ReadMatrix(reader, matrixType);
            }
        }

        /// <summary>
        /// Reads an <see cref="Matrix"/> from a <see cref="TextReader"/>.
        /// </summary>
        /// <param name="reader">The <see cref="TextReader"/> to read the matrix from.</param>
        /// <param name="matrixType">The type of matrix to return. </param>
        /// <returns>A matrix containing the data from the <see cref="TextReader"/>. <b>null</b> is returned if the <see cref="TextReader"/> is empty.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="reader"/> is <b>null</b>.</exception>
        /// <exception cref="FormatException">If a value is not a number or not in a valid format.</exception>
        /// <exception cref="OverflowException">If a value represents a number less than <see cref="Double.MinValue"/> or greater than <see cref="Double.MaxValue"/>.</exception>
        public Matrix ReadMatrix(TextReader reader, MatrixType matrixType)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader", Strings.NullParameterException);
            }

            ArrayList data = new ArrayList();

            //max is used to supports files like:
            //1,2
            //3,4,5,6
            //7
            //this creates a 3x4 matrix:
            //1, 2, 0 ,0 
            //3, 4, 5, 6
            //7, 0, 0, 0
            int max = -1;

            string line = reader.ReadLine();
            while (line != null)
            {
                line = line.Trim();
                if (line.Length > 0)
                {
                    string[] row = delimiter.Split(line);
                    max = System.Math.Max(max, row.Length);
                    data.Add(row);
                }
                line = reader.ReadLine();
            }

            Matrix ret = null;

            if (data.Count != 0)
            {
                ret = MatrixBuilder.CreateMatrix(data.Count, max, matrixType);
                string[] row;
                for (int i = 0; i < data.Count; i++)
                {
                    row = (string[])data[i];
                    for (int j = 0; j < row.Length; j++)
                    {
                        ret[i, j] = Double.Parse(row[j], NumberStyles.Any, null);
                    }
                }
            }

            return ret;
        }

        #endregion
    }
}
